const createHanziWriterContext = require('hanzi-writer-miniprogram')
import pinyin from 'wl-pinyin'

Component({
    data: {
        active: 1,
        writerCtx: null,
        content: '你',
        pinyinText: ''
    },
    methods: {
        // 事件处理函数
        menuChange(e: any) {
            // @ts-ignore
            this.setData({active: e.detail});
            switch (e.detail) {
                case 0:
                    wx.navigateTo({
                        url: `../index/index`
                    })
                    break;
            }
        },
        showHz() {
            // @ts-ignore
            this.writerCtx.showCharacter();
        },
        hideHz() {
            // @ts-ignore
            this.writerCtx.hideCharacter();
        },
        playHz() {
            // @ts-ignore
            this.writerCtx.loopCharacterAnimation();
        },
        randomHz() {
            wx.request({
                url:'https://wxapi.db101.cn/v1/hz/random',
                success: (res) => {
                    // @ts-ignore
                    this.content = res.data;
                    // @ts-ignore
                    this.writerCtx.setCharacter(res.data)
                    // @ts-ignore
                    this.pinyin();
                }
            })
        },
        quizHz() {
            // @ts-ignore
            this.writerCtx.quiz();
        },
        pinyin() {
            // @ts-ignore
            this.setData({pinyinText: pinyin.getPinyin(this.content)});
        },
        playAudio() {
            // @ts-ignore
            this.innerAudioContext.src = `https://wxapi.db101.cn/voice/${this.content}.mp3`;
            // @ts-ignore
            this.innerAudioContext.play();
        }
    },
    lifetimes: {
        attached: function () {
            // 在组件实例进入页面节点树时执行
            // @ts-ignore
            this.writerCtx = createHanziWriterContext({
                id: 'hz-writer',
                // @ts-ignore
                character: this.content,
                page: this,
                strokeColor: '#768d38',
            });

            // @ts-ignore
            this.pinyin();

            // @ts-ignore
            this.innerAudioContext = wx.createInnerAudioContext({
                useWebAudioImplement: true
            })

            // You can call any normal HanziWriter method here
            // @ts-ignore
            // this.writerCtx.loopCharacterAnimation();
        },
        detached: function () {
            // 在组件实例被从页面节点树移除时执行
        },
    }
})
